/*
 * IM - Image I/O Library
 * Copyright (c) 1996 CENPES/Petrobras, TeCGraf/PUC-Rio.
 * Antonio E. Scuri - scuri@tecgraf.puc-rio.br
 * 
 * COLOR.C
 * 
 * Contains the implementation of the color encoding/decoding functions.
 *
 * History:
 *          1996.06.14 - Finished inicial version.
 *
 */

#include "im.h"


long imEncodeColor(unsigned char Red, unsigned char Green, unsigned char Blue)
{
	return (((long)Red) << 16) | (((long)Green) << 8) | ((long)Blue);
}

void imDecodeColor(unsigned char* Red, unsigned char* Green, unsigned char* Blue, long Color)
{
	if (Red) *Red = (unsigned char)(Color >> 16);
	if (Green) *Green = (unsigned char)(Color >> 8);
	if (Blue) *Blue = (unsigned char)Color;
}

void imMap2RGB(int width, int height, unsigned char *map, int pal_size, long *colors, unsigned char *red, unsigned char *green, unsigned char *blue)
{
  int x, y, c, index;
  unsigned char r[256], g[256], b[256];

  for (c = 0; c < pal_size; c++)
    imDecodeColor(&r[c], &g[c], &b[c], colors[c]);

  for (y = 0; y < height; y++)
  {
    for (x = 0; x < width; x++)
    {
      index = *map++;
      *red++ = r[index];
      *green++ = g[index];
      *blue++ = b[index];
    }
  }
}

void imRGB2Gray(int width, int height, unsigned char *red, unsigned char *green, unsigned char *blue, unsigned char *map, long *grays)
{
  int x, y, c;

  for (c = 0; c < 256; c++)
    *grays++ = imEncodeColor((unsigned char)c, (unsigned char)c, (unsigned char)c);

  for (y = 0; y < height; y++)
  {
    for (x = 0; x < width; x++)
      *map++ = (unsigned char)((*red++ * 30 + *green++ * 59 + *blue++ * 11) / 100);
  }
}

void imMap2Gray(int width, int height, unsigned char *color_map, int pal_size, long *colors, unsigned char *gray_map, long *grays)
{
  int x, y, c;
  unsigned char cnv_table[256];
  unsigned char r, g, b;

  for (c = 0; c < 256; c++)
    *grays++ = imEncodeColor((unsigned char)c, (unsigned char)c, (unsigned char)c);

  for (c = 0; c < pal_size; c++)
  {
    imDecodeColor(&r, &g, &b, colors[c]);
    cnv_table[c] = (unsigned char)((r * 30 + g * 59 + b * 11) / 100);
  }

  for (y = 0; y < height; y++)
  {
    for (x = 0; x < width; x++)
      *gray_map++ = cnv_table[*color_map++];
  }
}
